using MediatR;
using Microsoft.AspNetCore.Mvc;
using Medical.ErrorCode;
using BaseData.ErrorCode;
using Medical.ReadApi.Dto;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Dto;

namespace Medical.WriteApi.Controllers
{
	/// <summary>
	/// 授权管理控制器（写操作）- 角色和权限管理
	/// </summary>
	[ApiController]
	[Route("api/[controller]/[action]")]
	public class AuthorizationController : ControllerBase
	{
		private readonly IMediator _mediator;
		
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="mediator">MediatR中介者</param>
		public AuthorizationController(IMediator mediator)
		{
			_mediator = mediator;
		}

		/// <summary>
		/// 创建角色
		/// </summary>
		/// <param name="command">创建角色命令，包含角色名称和描述</param>
		/// <returns>创建成功的角色信息</returns>
		/// <remarks>
		/// 示例请求:
		/// POST /api/Authorization/CreateRole
		/// {
		///   "name": "管理员",
		///   "description": "系统管理员角色"
		/// }
		/// </remarks>
		/// <response code="200">创建成功，返回角色信息</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPost]
		[ProducesResponseType(typeof(ApiResult<RoleDto>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<RoleDto>> CreateRole([FromBody] CreateRoleCommand command)
		{
			try { var data = await _mediator.Send(command); return new ApiResult<RoleDto> { Code = ApiEnum.新增成功, Message = "创建成功", data = data }; }
			catch (Exception ex) { return new ApiResult<RoleDto> { Code = ApiEnum.新增失败, Message = ex.Message, data = null }; }
		}

		/// <summary>
		/// 更新角色信息
		/// </summary>
		/// <param name="command">更新角色命令，包含角色ID和要更新的字段</param>
		/// <returns>更新后的角色信息</returns>
		/// <remarks>
		/// 示例请求:
		/// PUT /api/Authorization/UpdateRole
		/// {
		///   "roleId": 1,
		///   "name": "新角色名",
		///   "description": "新描述"
		/// }
		/// </remarks>
		/// <response code="200">更新成功，返回更新后的角色信息</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">角色不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPut]
		[ProducesResponseType(typeof(ApiResult<RoleDto>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<RoleDto>> UpdateRole([FromBody] UpdateRoleCommand command)
		{
			try { var data = await _mediator.Send(command); return new ApiResult<RoleDto> { Code = ApiEnum.更新成功, Message = "更新成功", data = data }; }
			catch (Exception ex) { return new ApiResult<RoleDto> { Code = ApiEnum.更新失败, Message = ex.Message, data = null }; }
		}

		/// <summary>
		/// 删除角色
		/// </summary>
		/// <param name="roleId">角色ID</param>
		/// <returns>删除操作是否成功</returns>
		/// <remarks>
		/// 示例请求:
		/// DELETE /api/Authorization/DeleteRole?roleId=1
		/// 
		/// 注意：删除角色会同时删除该角色的所有权限关联和用户角色关联。
		/// </remarks>
		/// <response code="200">删除成功</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">角色不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpDelete]
		[ProducesResponseType(typeof(ApiResult<bool>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<bool>> DeleteRole([FromQuery] long roleId)
		{
			try { var ok = await _mediator.Send(new DeleteRoleCommand { RoleId = roleId }); return new ApiResult<bool> { Code = ApiEnum.删除成功, Message = "删除成功", data = ok }; }
			catch (Exception ex) { return new ApiResult<bool> { Code = ApiEnum.删除失败, Message = ex.Message, data = false }; }
		}

		/// <summary>
		/// 为角色分配权限（会覆盖原有权限）
		/// </summary>
		/// <param name="command">分配权限命令，包含角色ID和权限ID列表</param>
		/// <returns>分配操作是否成功</returns>
		/// <remarks>
		/// 示例请求:
		/// POST /api/Authorization/AssignPermissions
		/// {
		///   "roleId": 1,
		///   "permissionIds": [1, 2, 3, 4]
		/// }
		/// 
		/// 注意：此操作会先删除角色原有的所有权限关联，然后分配新的权限。
		/// </remarks>
		/// <response code="200">分配成功</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">角色不存在或权限不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPost]
		[ProducesResponseType(typeof(ApiResult<bool>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<bool>> AssignPermissions([FromBody] AssignPermissionsToRoleCommand command)
		{
			try { var ok = await _mediator.Send(command); return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "分配成功", data = ok }; }
			catch (Exception ex) { return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false }; }
		}

		/// <summary>
		/// 为员工分配角色（会覆盖原有角色）
		/// </summary>
		/// <param name="command">分配角色命令，包含员工ID和角色ID列表</param>
		/// <returns>分配操作是否成功</returns>
		/// <remarks>
		/// 示例请求:
		/// POST /api/Authorization/AssignRoles
		/// {
		///   "employeeId": 1,
		///   "roleIds": [1, 2]
		/// }
		/// 
		/// 注意：此操作会先删除员工原有的所有角色关联，然后分配新的角色。
		/// </remarks>
		/// <response code="200">分配成功</response>
		/// <response code="400">请求参数错误</response>
		/// <response code="404">员工不存在或角色不存在</response>
		/// <response code="500">服务器内部错误</response>
		[HttpPost]
		[ProducesResponseType(typeof(ApiResult<bool>), 200)]
		[ProducesResponseType(400)]
		[ProducesResponseType(404)]
		[ProducesResponseType(500)]
		public async Task<ApiResult<bool>> AssignRoles([FromBody] AssignRolesToEmployeeCommand command)
		{
			try { var ok = await _mediator.Send(command); return new ApiResult<bool> { Code = ApiEnum.更新成功, Message = "分配成功", data = ok }; }
			catch (Exception ex) { return new ApiResult<bool> { Code = ApiEnum.更新失败, Message = ex.Message, data = false }; }
		}
	}
}
